<?php
/**
 *	KLF Framework
 *
 *	Written by Kristian Oye <kristianoye@gmail.com> on Oct 30, 2011
 *	Copyright (C) 2010-2011
 */
namespace KLF\System\Config
{
	/**
	 *  Class KDomainConfiguration extends KConfig
	 *
	 *  Contains a set of application configurations for a particular domain.
	 *
	 *  @package KLF\System\Config
	 *  @access public
	 *  @author Kristian Oye <kristianoye@gmail.com>
	 *  @since 0.1
	 *
	 *  @method KDomainConfiguration extends KConfig NewInstance
	 */
	use KLF\System\Web\KHttpRequest;

	class KDomainConfiguration extends KConfiguration
	{
		/**
		 * Construct a domain configuration.
		 * 
		 * 
		 * @param string|array $config
		 */
		public function __construct($config)
		{
			parent::__construct($config);
		}
		
		/**
		 * Get an application by hostname.
		 *
		 * @author Kristian Oye <kristianoye@gmail.com>
		 * @since 0.1
		 * @return KWebApplicationConfiguration The host web application configuration.
		*/
		public function GetHostConfiguraiton($hostName)
		{
			$hosts = $this->GetValue('hosts', array());
			
			if (isset($hosts[$hostName]))
			{
				//  Allow for hostname aliases in configuration.
				if (is_string($hosts[$hostName]))
				{
					return $this->GetHostConfiguraiton($hosts[$hostName]);
				}
				/* @var $config KWebApplicationConfiguration */
				$config = $hosts[$hostName];
				if (!$config->IsInitialized)
				{
					$config->Initialize($this->BaseDirectory, $this->ConfigurationDirectory);
				}
				return $config;
			}
			else
			{
				$defaultHost = $this->GetValue('defaultHost', '');
				$allowDefault = $this->GetValue('allowDefaultHost', true);
				
				if ($allowDefault === false || strlen($defaultHost) === 0 || !isset($hosts[$defaultHOst]))
				{
					throw new KHostNotFoundException($hostName);
				}
				else
				{
					return $this->GetHostConfiguraiton($defaultHost);
				}
			}
		}
		
		/**
		 * Determine which host application configuration to use based on 
		 * the incoming HTTP request.
		 */
		public function GetHostConfigurationFromRequest()
		{
			$request = KHttpRequest::GetCurrentRequest();
			
			return $this->GetHostConfiguraiton($request->HostName);
		}
	}
}